<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class My_model extends Model{
    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    public function saveData($table , $data){
        $data       = arrayEmpty($data);
        if(empty($data)){
            return false;
        }
        $query      = Db::name($table);

        $data       = count($data) == count($data , 1) ? [ $data ] : $data;

        list($insertData , $updateData)         = $this->_handleData($data);

        if(!empty($insertData)){
            if(count($insertData) == count($insertData , 1) && count($insertData) == 1){
                return $query->insertGetId(rest($insertData));
            }

            return $query->insertAll($data);
        }

        return $this->_updateData($table , $updateData);

    }

    private function _handleData($data){
        $insertData         = [];
        $updateData         = [];

        foreach($data as $dk => $dv){
            if(isset($dv['id']) && $dv['id']){
                $updateData[]       = $dv;
                continue;
            }
            unset($dv['id']);

            $insertData[]           = $dv;
        }

        return [ $insertData  ,$updateData ];
    }

    private function _updateData($table , $data){
        $result             = [];
        foreach($data as $dv){
            $result[]       = Db::name($table)->where([ 'id' => $dv['id'] ])->limit(1)->update($dv);
        }

        return $result;
    }
}